﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using DAL;

namespace PreBuildGrupyz
{
    public partial class UploadFiles : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void btnUpload_Click(object sender, EventArgs e)
        {
            if (FileUpload1.PostedFile != null)
            {
                try
                {
                    HttpPostedFile myFile = FileUpload1.PostedFile;
                    string strFilename = Path.GetFileName(myFile.FileName);
                    string path = "~/content/images/" + strFilename;
                    if (!File.Exists(Server.MapPath(path)))
                        myFile.SaveAs(Server.MapPath(path));

                    UpdateDatabase(path, int.Parse(Request.QueryString["ProductId"]));
                }
                catch (Exception)
                {
                    throw;
                }

            }
            else
            {
                //no file
            }
        }

        private void UpdateDatabase(string path, int ProductId)
        {
            try
            {
                GrupyzEntities gr = new GrupyzEntities();
                var prod = (from x in gr.Artigo
                           where x.Id == ProductId
                           select x).SingleOrDefault();
                prod.Imagem = path;
                gr.SaveChanges();

                Response.Write("<script>self.parent.location.reload(true);</script>");

            }
            catch (Exception ex)
            {                
                throw new Exception(ex.Message);
            }
        }
    }
}